﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using System.Web.Http.Results;
using WebApp.BLL.Manage;
using WebApp.BLL.Service;
using WebApp.Common;
using WY.WebApi.Models.Request;
using WY.WebApi.Models.Result;

namespace WY.WebApi.Controllers
{
    /// <summary>
    /// 未登录状态下账户相关操作接口
    /// </summary>
    [RoutePrefix("api/account")]
    public class AccountPublicApiController : ApiController
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region Options

        [ApiExplorerSettings(IgnoreApi = true)]
        public string Options()
        {

            return null; // HTTP 200 response with empty body

        }

        #endregion

        #region Login

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [Route("login")]
        [AllowAnonymous]
        public JsonResult<LoginResult> Login(LoginRequest model)
        {
            var result = new LoginResult();

            #region 参数验证

            var errorList = new List<string>();
            if (!ModelState.IsValid)
            {
                foreach (var v in ModelState)
                {
                    foreach (var err in v.Value.Errors)
                    {
                        errorList.Add(err.ErrorMessage);
                    }
                }
            }
            if (errorList.Count > 0)
            {
                result.ret = ApiResultBase.RESULT_ERROR;
                result.message = string.Join("\n", errorList.ToArray());
                return Json(result);
            }

            #endregion

            var userservice = new S_userService();

            string errmsg = "";
            var user = userservice.ApiLogin(model.username, model.password, out errmsg);

            if (user == null)
            {
                result.ret = ApiResultBase.RESULT_ERROR;
                result.message = errmsg;
                return Json(result);
            }

            result.userId = user.Id;
            result.username = user.Username;
            //生成Access_token，有效期1天
            result.access_token = new AccessTokenService().CreateAccessToken(user.Id.ToString(), DateTime.Now.AddDays(1));

            return Json(result);
        }

        #endregion

    }
}
